package com.sjf.reggie.controller;

import com.sjf.common.Result;
import com.sjf.reggie.entity.User;
import com.sjf.reggie.service.UserService;
import com.sjf.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.concurrent.TimeUnit;

/**
 * 用户 控制器
 *
 * @author <huangtang>
 * @since 2022/4/27 0:28
 **/
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate<Object,Object> redisTemplate;

    /**
     * 生成随机6位验证码
     * @return
     */
    @PostMapping("/sendMsg")
    public Result<String> sendMsg( @RequestBody User user, HttpSession session ){
        Integer code = ValidateCodeUtils.generateValidateCode (6);
        log.info ("手机号 {} 的 验证码：{}",user.getPhone (), code);
        //session.setAttribute ("code",code.toString ());
        //将生成的验证码放入Redis中
        redisTemplate.opsForValue ().set(user.getPhone (), code.toString (), 5, TimeUnit.MINUTES);
        return Result.success ("验证码发送成功");
    }

    @GetMapping("/login")
    public Result<User> login(  String phone,
                                  String code, HttpServletRequest request){
        log.info ("用户登录：{} , 验证码:{}", phone,code);
        User user = userService.login (request,phone, code);
        return Result.success (user);
    }

    @PostMapping("/loginout")
    public Result<String> logout(HttpSession session){
        log.info ("用户退出登录");
        //销毁session
        session.removeAttribute ("user");
        return Result.success ("退出成功");
    }
}
